import utils.TreeNode;

/**
 * @Author ZhangCuirong
 * @Date 2025/8/4 13:30
 * @description:
 */
public class Solution236 {
    public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {
        if (root == p || root == q || root == null) {
            return root;
        }
        TreeNode left = lowestCommonAncestor(root.left, p, q);
        TreeNode right = lowestCommonAncestor(root.right, p, q);
        if (left != null && right != null) {
            return root;
        }
        if (left == null && right == null) return null;
        return left != null ? left : right;
    }

    public static void main(String[] args) {
        Solution236 solution = new Solution236();
        TreeNode root = TreeNode.buildTree(new int []{3,5,1,6,2,0,8,-1,-1,7,4});
        TreeNode p = TreeNode.findNode(root,5);
        TreeNode q = TreeNode.findNode(root,1);

        TreeNode treeNode = solution.lowestCommonAncestor(root, p, q);
        System.out.println(treeNode.val);
    }
}
